import React, { Component, PropTypes } from 'react';
import { Router, Route } from 'react-router';
import ScanGroup from './ScanGroup';
import styles from './RequireBarCode.less';
import comm from './common.less';
import barcode from './assets/barcode.png';
import Loading from './Loading/Loading';
import { message } from 'antd';
import AccruePoints from '~/services/Accruepoints';

class RequireBarCode extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
    }
    const object = this.props.location.state;
    if (!object.code) {
      this.context.router.push('/')
    }
    this.userinfo = object;
    this.pointsList = object.PointList || [];
  }
  /**
   * [onCallBack 扫码回调方法]
   * @param  {[type]} barcode [产品条形码]
   * @param  {[type]} score        [description]
   * @return {[type]}              [description]
   */
  onCallBack = (code) => {
    Loading.show();
    AccruePoints.accruePoints({
      memPhone: this.userinfo.mobilephone,
      userName: this.userinfo.userPhone,
      fwcode: this.userinfo.code,
      barcode: code,
    }).then(data => {
      Loading.hide();
      const singleScore = parseInt(data.accruedPointsTotal, 10);
      this.pointsList.push({
        name: data.productName,
        score: singleScore,
      });
      this.userinfo.score = data.productPointsBalance;
      this.context.router.push({
        pathname: '/',
        state: Object.assign(this.userinfo, {
          PointList: this.pointsList,
        }),
      })
    }).catch(err => {
      Loading.hide();
      message.error(err.errorMsg || '系统繁忙，请稍后重试')
    })
  }
  onSubmit = (e) => {
    const code = this.refs.scan.state.securityCode;
    if (code === 13) {
      this.onCallBack(code)
    }
  }
  render() {
    return <div>
            <div className={`${comm.textcenter} ${styles.header}`}>
              <p className={styles.blue}>
              该产品为汤臣倍健正品，防伪码信息不完整
              </p>
              <p>请继续输入瓶身条形码完成积分</p>
            </div>

             <ScanGroup ref="scan" callback={this.onCallBack} placeholder="请输入13位瓶身条形码" />
             <div className={comm.textcenter}>
               <button className={styles.finishButton} onClick={this.onSubmit}>提 交</button>
             </div>
             <div className={`${comm.textcenter}`}>
               <img src={barcode} className={styles.image} />
             </div>

           </div>
  }
}

RequireBarCode.propTypes = {
};
RequireBarCode.contextTypes = {
  router: PropTypes.object,
}

export default RequireBarCode;
